package com.file.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.file.mapper.UserMapper;
import com.file.pojo.User;
import com.file.pojo.department;
import com.file.vo.PageResult;
import com.file.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /*
    * 用户登录
    * */
    public String login(User user) {
        String password = user.getPassword();
        //md5hash相对于md5更加"安全" 没有绝对安全的系统!!!
        String md5Pass =
                DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Pass);
        //根据其中不为null的数据当做where条件 u/p
        //Sql: select * from user where u=#{u} and p=#{p}
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>(user);
        User userDB = userMapper.selectOne(queryWrapper);
        if (userDB == null) {
            //没有查询到数据
            return null;
        }
        String token = UUID.randomUUID().toString()
                .replace("-", "");
        return token;
    }

    /**
     * 分页效果
     * @param pageResult
     * @return
     */
    @Override
    public PageResult getuserlist(PageResult pageResult) {
        IPage<User> iPage = new Page<User>(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "username", pageResult.getQuery());
        iPage = userMapper.selectPage(iPage,queryWrapper);
        long total = iPage.getTotal();
        List<User> list = iPage.getRecords();
        return pageResult.setRows(list).setTotal(total);
    }
}
